/**
* 运维工具  监控脚本
*/
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>监控脚本</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="formInline" class="user-search">
      <el-form-item>
        <el-select size="small" v-model="formInline.hostlist" placeholder="请选择主机">
          <el-option v-for="type in hostlist" :label="type.host_name_ip" :value="type.host_ip" :key="type.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="">
        <el-input size="small" v-model="formInline.var_name" placeholder="输入变量名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleEdit()">添加</el-button>
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table size="small" :data="listData" highlight-current-row v-loading="loading" border
              element-loading-text="拼命加载中" style="width: 100%;">
      <!--      <el-table-column align="center" type="selection" width="60">-->
      <!--      </el-table-column>-->
      <el-table-column align="center" type="index" width="60">
      </el-table-column>
      <el-table-column sortable prop="py_title" label="脚本名称" width="120">
      </el-table-column>
      <el-table-column sortable prop="file_name" label="文件名称" width="120">
      </el-table-column>
      <el-table-column sortable prop="py_describe" label="脚本描述" width="300">
      </el-table-column>
      <el-table-column sortable prop="py_timer" label="定时器" width="120">
      </el-table-column>
      <el-table-column sortable prop="py_status_name" label="状态" width="80">
      </el-table-column>
      <el-table-column sortable prop="host_ip" label="主机IP" width="120">
      </el-table-column>
      <el-table-column sortable prop="start_time" label="启动时间" width="200">
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="120">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="deleteUser(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>
    <!-- 编辑界面 -->
    <el-dialog title="修改" :visible.sync="editFormVisible" width="30%" @click="closeDialog">
      <el-form label-width="120px" :model="editForm" ref="editForm">
        <el-form-item label="上传文件" prop="py_title" v-show='file_xs'>
          <!--          <input type="file" id="fileinput" ref="myfile"/>-->
          <input class="file" name="file" type="file" accept="image/png,image/gif,image/jpeg" ref="myfile"/>
          <!--          <el-input size="small" type="file" v-model="editForm.py_bytes" placeholder="上传文件"></el-input>-->
        </el-form-item>
        <el-form-item label="脚本名称" prop="py_title">
          <el-input size="small" v-model="editForm.py_title" auto-complete="off" placeholder="脚本名称"></el-input>
        </el-form-item>
        <el-form-item label="文件名称" prop="file_name" v-show='file_xs'>
          <el-input size="small" v-model="editForm.file_name" auto-complete="off" placeholder="文件名称"></el-input>
        </el-form-item>
        <el-form-item label="脚本描述" prop="py_describe">
          <el-input size="small" v-model="editForm.py_describe" auto-complete="off" placeholder="脚本描述"></el-input>
        </el-form-item>
        <el-form-item label="定时器" prop="py_timer">
          <el-input size="small" v-model="editForm.py_timer" auto-complete="off" placeholder="请输入间隔的时间(秒)"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="py_status" v-show='py_zt'>
          <el-select size="small" v-model="editForm.py_status" placeholder="请选择">
            <el-option v-for="type in status_list" :label="type.py_status" :value="type.id" :key="type.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="主机IP" prop="editForm.host_ip" v-show='file_xs'>
          <el-select size="small" v-model="editForm.host_ip" placeholder="请选择">
            <el-option v-for="type in hostlist" :label="type.host_ip" :value="type.host_ip" :key="type.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="submitForm('editForm')">保存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  devHostList,
  monitorpySave,
  monitorpyAdd,
  monitorpyList,
  monitorpyPage,
  monitorpyDelete,
  monitorpySearch
} from '../../api/devMG'
import Pagination from '../../components/Pagination'

export default {
  data() {
    return {
      nshow: true, //switch开启
      fshow: false, //switch关闭
      loading: false, //是显示加载
      editFormVisible: false, //控制编辑页面显示与隐藏
      title: '添加',
      editForm: {
        id: '',
        host_ip: '',
        py_title: '',
        file_name: '',
        py_describe: '',
        py_status: '',
        py_timer: '',
        start_time: '',
        py_status_name: '',
        token: localStorage.getItem('logintoken')
      },
      formInline: {
        page: 1,
        limit: 10,
        py_bytes: '',
        py_title: '',
        file_name: '',
        py_describe: '',
        py_status: '',
        py_status_name: '',
        py_timer: '',
        host_ip: '',
        start_time: '',
        hostlist: '',
        token: localStorage.getItem('logintoken')
      },
      // 删除
      seletedata: {
        ids: '',
        token: localStorage.getItem('logintoken')
      },
      userparm: [], //搜索权限
      listData: [], //用户数据
      file_xs: true,
      py_zt: true,
      // 分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 10,
        total: 10
      },
      hostlist: [
        {host_ip: '请选择', id: 0},
        {host_ip: '已处理', id: 1},
        {host_ip: '未处理', id: 2},
        // {id: 16, host_name_ip: "吴金波赞助_139.224.252.227"},
        // {id: 17, host_name_ip: "李明轩赞助_101.132.138.55"}
      ],
      status_list: [
        {py_status: '启动', id: 0},
        {py_status: '关闭', id: 1},
        // {id: 16, host_name_ip: "吴金波赞助_139.224.252.227"},
        // {id: 17, host_name_ip: "李明轩赞助_101.132.138.55"}
      ],
    }
  },
  // 注册组件
  components: {
    Pagination
  },
  /**
   * 数据发生改变
   */
  computed: {
    selectParams() { // 当下面的属性变化时，本计算属性会重新计算，得到一个params对象，用于后续传递给axios
      return {
        var_lable__icontains: this.formInline.hostlist || '',
        var_name__icontains: this.formInline.var_name || '',
      };
    },
  },

  watch: {
    selectParams() { // 监听计算属性，当计算属性发生变化向后端发送请求
      monitorpySearch(this.selectParams).then(res => {
        this.listData = res.data.results
        this.listLoading = false
      })
    }
  },

  /**
   * 创建完毕
   */

  created() {
    this.getdata(this.formInline)
  },

  /**
   * 里面的方法只有被调用才会执行
   */

  methods: {
    // 获取数据方法
    getdata(parameter) {
      this.loading = true
      /***
       * 调用接口，注释上面模拟数据 取消下面注释
       */
      monitorpyList(parameter)
        .then(res => {
          this.loading = false
          if (res.success == false) {
            this.$message({
              type: 'info',
              message: res.msg
            })
          } else {
            this.listData = res.data.results
            // 分页赋值
            this.pageparm.currentPage = this.formInline.page
            this.pageparm.pageSize = this.formInline.limit
            this.pageparm.total = res.data.count
            monitorpyPage(this.pageparm).then(res => {
              this.listData = res.data.results
            })
          }
        })
        .catch(err => {
          this.loading = false
          this.$message.error('菜单加载失败，请稍后再试！')
        })

      devHostList(parameter)
        .then(res => {
          this.loading = false
          if (res.success == false) {
            this.$message({
              type: 'info',
              message: res.msg
            })
          } else {
            this.hostlist = res.data
          }
        })
    },

    // 分页插件事件
    callFather(parm) {
      this.formInline.page = parm.currentPage
      this.formInline.limit = parm.pageSize
      this.getdata(this.formInline)
    },
    // 搜索事件
    search() {
      this.getdata(this.formInline)
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      this.editFormVisible = true
      console.log(row)
      if (row != undefined && row != 'undefined') {
        this.file_xs = false
        this.update_add = true
        this.title = '修改'
        this.editForm.id = row.id
        this.editForm.file_name = row.file_name
        this.editForm.py_title = row.py_title
        this.editForm.py_describe = row.py_describe
        this.editForm.py_timer = row.py_timer
        this.editForm.py_status = row.py_status
        this.editForm.host_ip = row.host_ip
      } else {
        this.py_zt = false
        this.update_add = false
        this.title = '添加'
        this.editForm.id = ''
        this.editForm.py_bytes = ''
        this.editForm.py_title = ''
        this.editForm.py_describe = ''
        this.editForm.py_timer = ''
        this.editForm.py_status = ''
        this.editForm.edit_user = JSON.parse(localStorage.getItem('userdata'))['username_id'] * 1
      }
    },

    // 编辑、增加页面保存方法
    submitForm(editData) {
      this.$refs[editData].validate(valid => {
        if (this.update_add) {
          monitorpySave(this.editForm)
            .then(res => {
              this.editFormVisible = false
              this.loading = false
              if (res.success) {
                this.getdata(this.formInline)
                this.$message({
                  type: 'success',
                  message: '监控脚本保存成功！'
                })
              } else {
                this.$message({
                  type: 'info',
                  message: res.msg
                })
              }
            })
            .catch(err => {
              this.editFormVisible = false
              this.loading = false
              this.$message.error('监控脚本保存失败，请稍后再试！')
            })
        } else {
          let myfile = this.$refs.myfile.files[0]
          let fromdata = new FormData()
          fromdata.append('myfile', myfile)
          for (var x in this.editForm) {
            fromdata.append(x, this.editForm[x])
          }
          let config = {
            headers: {'Content-Type': 'multipart/form-data'} //这里是重点，需要和后台沟通好请求头，Content-Type不一定是这个值
          };
          //添加请求头
          // this.editFormVisible = false
          // this.loading = false
          // axios.post('http://127.0.0.1:9001/v1/api/dev/monitorpy/upload_file/', fromdata, config)
          //   .then(response => {
          //     console.log(response.data);
          //   })

          monitorpyAdd(fromdata)
            .then(res => {
              this.editFormVisible = false
              this.loading = false
              if (res.success) {
                this.getdata(this.formInline)
                this.$message({
                  type: 'success',
                  message: '监控脚本新增成功！'
                })
              } else {
                this.$message({
                  type: 'info',
                  message: res.msg
                })
              }
            })
          .catch(err => {
            this.editFormVisible = false
            this.loading = false
            this.$message.error('监控脚本保存失败，请稍后再试！')
          })

          // monitorpyAdd(param)
          // monitorpyAdd(fromdata)
          //   .then(res => {
          //     this.editFormVisible = false
          //     this.loading = false
          //     if (res.success) {
          //       this.getdata(this.formInline)
          //       this.$message({
          //         type: 'success',
          //         message: '主机新增成功！'
          //       })
          //     } else {
          //       this.$message({
          //         type: 'info',
          //         message: res.msg
          //       })
          //     }
          //   })
          //   .catch(err => {
          //     this.editFormVisible = false
          //     this.loading = false
          //     this.$message.error('监控脚本保存失败，请稍后再试！')
          //   })
        }
      })
    },
    // 删除权限
    deleteUser(index, row) {
      this.$confirm('确定要删除吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          monitorpyDelete(row.id)
            .then(res => {
              if (res.success) {
                this.$message({
                  type: 'success',
                  message: '系统环境变量已删除'
                })
                this.getdata(this.formInline)
              } else {
                this.$message({
                  type: 'info',
                  message: res.msg
                })
              }
            })
            .catch(err => {
              this.loading = false
              this.$message.error('系统环境变量删除失败，请稍后再试！')
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 关闭编辑、增加弹出框
    closeDialog() {
      this.editFormVisible = false
    }
  }
}
</script>

<style scoped>
.user-search {
  margin-top: 20px;
}

.userRole {
  width: 100%;
}
</style>

